package com.qf.qflivehou.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.qflivehou.pojo.vo.LiveUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Liu
 * @date 2022/1/10 20:32
 */
@Component
public class JwtUtils {
    //设置公钥信息
    @Value("${jwt.securt}")
    private String srcurt;
    @Value("${jwt.issuer}")
    private String issuer;
    @Value("${jwt.subject}")
    private String subject;

    //加密的方法
    public String createToken(LiveUser liveUser){
        //1.设置加密的算法,以及密钥
        Algorithm algorithm = Algorithm.HMAC256(srcurt);
        //2.我们需要设置头部信息
        Map map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        //3.生成token串
        String token = JWT.create().withHeader(map)
                .withIssuer(issuer)
                .withIssuedAt(new Date())
                .withSubject(subject)
                .withClaim("username", liveUser.getLoginName())
                .sign(algorithm);
        return token;
    }

    //解密的方法

    public  String verfiyToken(String token) {
        Algorithm algorithm1 = Algorithm.HMAC256(srcurt);
        JWTVerifier verifier = JWT.require(algorithm1).withIssuer(issuer).build();
        try {
            DecodedJWT verify = verifier.verify(token);
            //获取到自定义的内容
            Claim username = verify.getClaim("username");
            return username.asString();
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }
}
